//
//  PhotoManager.swift
//  letuofu
//
//  Created by Julien Yan on 2020/10/18.
//  Copyright © 2020 WH-JS. All rights reserved.
//

import Foundation
import Photos

class PhotoManager {
    
//    var albums : [Album] = []
    
    //获取相册访问授权，并获取相册
    func getPhotos(callback:@escaping ([Album])->()){
        PHPhotoLibrary.requestAuthorization { status in
            switch status {
            case .authorized:
                let collections = PHAssetCollection.fetchAssetCollections(with: .smartAlbum , subtype: .any, options: nil)
//                var maxPhotoAmount = 0
//                var maxPhotoAmountIndex = 0
                var albums = [Album]()
                collections.enumerateObjects { (collection, idx, stop) in
                    let album = Album(collection: collection)
//                    print(album.getAlbumName(),album.getPhotoCount())
                    let photoAmount = album.getPhotoCount()
                    if photoAmount > 0
                    {
                        albums.append(album)
//                        if photoAmount > maxPhotoAmount{
//                            maxPhotoAmountIndex = self.albums.count - 1
//                            maxPhotoAmount = photoAmount
//                        }
                    }
                }
                callback(albums)
//                self.photoNavigationController.albums = self.albums
//                self.selectedAlbumIndex = maxPhotoAmountIndex
//                self.showPhotoCollection()
            case .denied, .restricted:
                self.goToPhotoAccessSetting()
            case .notDetermined:
                self.goToPhotoAccessSetting()
            @unknown default:
                fatalError()
            }
        }
    }
    
    func goToPhotoAccessSetting(){
        let alert = UIAlertController(title: nil, message: "尚未获得相册的访问权限，是否前往授权？", preferredStyle: .alert)
        alert.addAction( UIAlertAction(title: "授权", style: .cancel, handler: { action in
            UIApplication.shared.openURL(NSURL(string:UIApplication.openSettingsURLString)! as URL)
        }))
        alert.addAction( UIAlertAction(title: "取消", style: .default))
        mainQueueAsync {
            UIViewController.topMostController()?.present(alert, animated: true, completion: nil)
        }
    }
}

class Album{
    
    private var collection: PHAssetCollection
    private var options:PHFetchOptions
    private(set) var poster : UIImage? = nil
    var identifier : String { get{return collection.localIdentifier}}
    
    init(collection: PHAssetCollection) {
        self.collection = collection
        options = PHFetchOptions()
        options.predicate = NSPredicate(format: "mediaType = %d",PHAssetMediaType.image.rawValue)
    }
    
    func getAlbumName() -> String{
        if let name = collection.localizedTitle{
            return name
        }else{
            return "(命名无法解析)"
        }
        
    }
    
    func getPhotos() -> [Photo]{
        let assetsFetchResults:PHFetchResult = PHAsset.fetchAssets(in: collection, options: options)
        var photoList = [Photo]()
        assetsFetchResults.enumerateObjects({ asset, idx, stop in
            photoList.append(Photo(asset: asset, index: idx))
        })
        return photoList
    }
    
    func getPhotoCount() -> Int{
        let collectionResult = PHAsset.fetchAssets(in: collection, options: options)
        return collectionResult.count
    }
    
    func getPosterPhoto(callback: @escaping (UIImage) -> Void) {
        if poster != nil {
            callback(poster!)
        }
        let assetsFetchResults:PHFetchResult = PHAsset.fetchAssets(in: collection, options: options)
        let firstPhoto = Photo(asset: assetsFetchResults.firstObject!, index: 0)
        firstPhoto.getThumbnail{ image in
            self.poster = image
            callback(image)
        }
    }
    
}


class Photo{
    
    private var asset: PHAsset
    var selected = false
    var selectedOrder: Int = 0
    var index: Int!
    private let compressedSize = 1000
    private let thumbnailSize = 123
    var identifier : String { get{ return asset.localIdentifier } }
    var thumbnailImage : UIImage? = nil
    
    init(asset: PHAsset,index: Int) {
        self.asset = asset
        self.index = index
    }
    
    func isImage() -> Bool{
        return asset.mediaType == PHAssetMediaType.image
    }
    
    func getOriginalImage(callback: @escaping (UIImage) -> Void) {
        let manager = PHImageManager.default()
        let option = PHImageRequestOptions()
        option.isSynchronous = true
        manager.requestImage(for: asset, targetSize:PHImageManagerMaximumSize, contentMode: .aspectFit, options: option) { (originImage, info) in
            callback(originImage!)
        }
    }
    
    func getCompressedImage(callback: @escaping (UIImage) -> Void) {
        let manager = PHImageManager.default()
        let option = PHImageRequestOptions()
        option.isSynchronous = true
        option.resizeMode = .fast
        manager.requestImage(for: asset, targetSize: CGSize.init(width: compressedSize, height: compressedSize), contentMode: .aspectFit, options: option) { (originImage, info) in
            callback(originImage!)
        }
    }
    
    func getThumbnail(callback: @escaping (UIImage) -> Void){
        if thumbnailImage != nil {
            callback(thumbnailImage!)
        }
        let manager = PHImageManager.default()
        let option = PHImageRequestOptions()
        option.isSynchronous = false
        option.deliveryMode = .highQualityFormat
        manager.requestImage(for: asset, targetSize: CGSize.init(width: thumbnailSize, height: thumbnailSize), contentMode: .aspectFit, options: option) { (thumbnailImage, info) in
            self.thumbnailImage = thumbnailImage
            callback(thumbnailImage!)
        }
    }
    
}
